package com.ruoyi.system.service.impl;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysQuestion;
import com.ruoyi.common.core.domain.entity.SysQuestionDomain;
import com.ruoyi.common.core.domain.entity.SysQuestionRecord;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.system.domain.SysCompanyReportReason;
import com.ruoyi.system.domain.SysCompanyReportSuggest;
import com.ruoyi.system.domain.SysNaire;
import com.ruoyi.system.domain.vo.BasisInfoVo;
import com.ruoyi.system.domain.vo.DomainInfoItemEditVo;
import com.ruoyi.system.domain.vo.DomainInfoItemVo;
import com.ruoyi.system.domain.vo.SysQuestionReqVo;
import com.ruoyi.system.dto.DiagnosePlanDto;
import com.ruoyi.system.dto.QuestionDomainScore;
import com.ruoyi.system.mapper.SysCompanyReportReasonMapper;
import com.ruoyi.system.mapper.SysCompanyReportSuggestMapper;
import com.ruoyi.system.mapper.SysDeptMapper;
import com.ruoyi.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.SysCompanyDiagnosisMapper;
import com.ruoyi.system.domain.SysCompanyDiagnosis;
import org.springframework.transaction.annotation.Transactional;
import utils.ScoreUtils;

import static com.ruoyi.common.utils.SecurityUtils.getLoginUser;

/**
 * 现场诊断记录Service业务层处理
 * 
 * @author ruoyi
 * @date 2023-09-11
 */
@Service
public class SysCompanyDiagnosisServiceImpl implements ISysCompanyDiagnosisService
{
    @Autowired
    private SysCompanyDiagnosisMapper sysCompanyDiagnosisMapper;

    @Autowired
    private SysDeptMapper deptMapper;


    @Autowired
    private ISysQuestionDomainService domainService;

    @Autowired
    private ISysQuestionService sysQuestionService;

    @Autowired
    private ISysNaireService sysNaireService;

    @Autowired
    private ISysQuestionRecordService sysQuestionRecordService;

    @Autowired
    private SysCompanyReportSuggestMapper sysCompanyReportSuggestMapper;
    @Autowired
    private SysCompanyReportReasonMapper sysCompanyReportReasonMapper;

    /**
     * 查询现场诊断记录
     *
     * @param deptId 现场诊断记录主键
     * @return 现场诊断记录
     */
    @Override
    public SysCompanyDiagnosis selectSysCompanyDiagnosisByCompanyId(Long deptId)
    {
        return sysCompanyDiagnosisMapper.selectSysCompanyDiagnosisByCompanyId(deptId);
    }

    /**
     * 查询现场诊断记录
     * 
     * @param diagnosisId 现场诊断记录主键
     * @return 现场诊断记录
     */
    @Override
    public SysCompanyDiagnosis selectSysCompanyDiagnosisByDiagnosisId(Long diagnosisId)
    {
        return sysCompanyDiagnosisMapper.selectSysCompanyDiagnosisByDiagnosisId(diagnosisId);
    }

    /**
     * 查询现场诊断记录列表
     * 
     * @param sysCompanyDiagnosis 现场诊断记录
     * @return 现场诊断记录
     */
    @Override
    public List<SysCompanyDiagnosis> selectSysCompanyDiagnosisList(SysCompanyDiagnosis sysCompanyDiagnosis)
    {
        return sysCompanyDiagnosisMapper.selectSysCompanyDiagnosisList(sysCompanyDiagnosis);
    }

    /**
     * 新增现场诊断记录
     * 
     * @param sysCompanyDiagnosis 现场诊断记录
     * @return 结果
     */
    @Override
    public int insertSysCompanyDiagnosis(SysCompanyDiagnosis sysCompanyDiagnosis)
    {
        sysCompanyDiagnosis.setCreateTime(DateUtils.getNowDate());
        return sysCompanyDiagnosisMapper.insertSysCompanyDiagnosis(sysCompanyDiagnosis);
    }

    /**
     * 修改现场诊断记录
     * 
     * @param sysCompanyDiagnosis 现场诊断记录
     * @return 结果
     */
    @Override
    public int updateSysCompanyDiagnosis(SysCompanyDiagnosis sysCompanyDiagnosis)
    {
        sysCompanyDiagnosis.setUpdateTime(DateUtils.getNowDate());
        return sysCompanyDiagnosisMapper.updateSysCompanyDiagnosis(sysCompanyDiagnosis);
    }

    /**
     * 批量删除现场诊断记录
     * 
     * @param diagnosisIds 需要删除的现场诊断记录主键
     * @return 结果
     */
    @Override
    public int deleteSysCompanyDiagnosisByDiagnosisIds(Long[] diagnosisIds)
    {
        return sysCompanyDiagnosisMapper.deleteSysCompanyDiagnosisByDiagnosisIds(diagnosisIds);
    }

    /**
     * 删除现场诊断记录信息
     * 
     * @param diagnosisId 现场诊断记录主键
     * @return 结果
     */
    @Override
    public int deleteSysCompanyDiagnosisByDiagnosisId(Long diagnosisId)
    {
        return sysCompanyDiagnosisMapper.deleteSysCompanyDiagnosisByDiagnosisId(diagnosisId);
    }

    @Override
    @Transactional
    public int diagnosisEnd(Long deptId){

        SysDept sysDept=deptMapper.selectDeptById(deptId);

        if(sysDept!=null){
            if(sysDept.getDiagnosePlan()!=null){
                List<DiagnosePlanDto> diagnosePlanDtos= JSONArray.parseArray(sysDept.getDiagnosePlan(),DiagnosePlanDto.class);
                boolean isExist=false;
                for (DiagnosePlanDto diagnosePlanDto:diagnosePlanDtos){
                    if(diagnosePlanDto.getWorkNote().equals("3")){
                        diagnosePlanDto.setNoteStatus("3");
                        isExist=true;
                        break;
                    }
                }
                if(!isExist){
                    DiagnosePlanDto diagnosePlanDto=new DiagnosePlanDto();
                    diagnosePlanDto.setNoteStatus("3");
                    diagnosePlanDto.setWorkNote("3");
                    diagnosePlanDtos.add(diagnosePlanDto);
                }


                sysDept.setDiagnosePlan(JSON.toJSONString(diagnosePlanDtos));

            }else{
                List<DiagnosePlanDto> diagnosePlanDtos=new ArrayList<>();
                DiagnosePlanDto diagnosePlanDto=new DiagnosePlanDto();
                diagnosePlanDto.setNoteStatus("3");
                diagnosePlanDto.setWorkNote("3");
                diagnosePlanDtos.add(diagnosePlanDto);

                sysDept.setDiagnosePlan(JSON.toJSONString(diagnosePlanDtos));
            }

            deptMapper.updateDept(sysDept);


            SysCompanyDiagnosis sysCompanyDiagnosis=sysCompanyDiagnosisMapper.selectSysCompanyDiagnosisByCompanyId(deptId);

            if(sysCompanyDiagnosis!=null){
                /**
                 * 计算现场评测表分数
                 */
                List<QuestionDomainScore> questionDomainScores=this.selectCompanyDiagnoseRecordScore(deptId,103L);

                BasisInfoVo basisInfoVo = JSONUtil.toBean(sysCompanyDiagnosis.getBasisInfo(), BasisInfoVo.class);

                List<DomainInfoItemVo> domainInfoItemVos = JSONUtil.toList(sysCompanyDiagnosis.getDomainInfo(), DomainInfoItemVo.class);

                BigDecimal totalScore=new BigDecimal("0.00");

                for (DomainInfoItemVo domainInfoItemVo:domainInfoItemVos){
                    for (QuestionDomainScore questionDomainScore:questionDomainScores) {
                        if(questionDomainScore.getDomainId().equals(domainInfoItemVo.getDomainId())){
                            System.out.println(questionDomainScore.toString());
                            domainInfoItemVo.setContent(questionDomainScore.getContent());
                            domainInfoItemVo.setResult(questionDomainScore.getScore());
                            totalScore.add(new BigDecimal(questionDomainScore.getScore()));
                            break;
                        }
                    }

                }
                basisInfoVo.setResult(totalScore.toString());

                sysCompanyDiagnosis.setBasisInfo(JSONUtil.toJsonStr(basisInfoVo));
                sysCompanyDiagnosis.setDomainInfo(JSONUtil.toJsonStr(domainInfoItemVos));
                return  sysCompanyDiagnosisMapper.updateSysCompanyDiagnosis(sysCompanyDiagnosis);

            }
        }
        return 0;
    }



    public List<QuestionDomainScore> selectCompanyDiagnoseRecordScore(Long companyId,Long naireId)
    {
        SysNaire naire = sysNaireService.selectSysNaireByNaireId(naireId);

        Set<Long> questionIdList = Arrays.stream(naire.getQuestions().substring(1, naire.getQuestions().length() - 1).split(","))
                .map(s -> Long.parseLong(s.trim()))
                .collect(Collectors.toSet());
//
//        for (Long element : questionIdList) {
//            System.out.println(element);
//        }

        List<SysQuestion> questions = sysQuestionService.selectSysQuestionByQuestionIds(questionIdList);

        SysQuestionRecord query=new SysQuestionRecord();
        query.setCompanyId(companyId);
        query.setNaireId(naireId);
      //  query.setUserId(getLoginUser().getUserId());
        List<SysQuestionRecord>  questionRecords=sysQuestionRecordService.selectSysQuestionRecordList(query);

        List<List<SysQuestionRecord>> resultList = ScoreUtils.groupDataByCondition(questionRecords,new Comparator<SysQuestionRecord>(){
            @Override
            public int compare(SysQuestionRecord o1, SysQuestionRecord o2) {
                return o1.getQuestionId().equals(o2.getQuestionId()) ? 0 : -1;
            }
        });

        System.out.println("====resultList.size()==="+resultList.size());
        if(CollUtil.isNotEmpty(questions)&&CollUtil.isNotEmpty(resultList)){
            for (SysQuestion question:questions){
                for (List<SysQuestionRecord> list : resultList) {
                    if(list.get(0).getQuestionId().equals(question.getQuestionId())){

                        question.setRecords(list);
                        break;
                    }
                }

            }
        }

        List<List<SysQuestion>> questionList= ScoreUtils.groupDataByCondition(questions,new Comparator<SysQuestion>(){
            @Override
            public int compare(SysQuestion o1, SysQuestion o2) {
                return o1.getDomain().equals(o2.getDomain()) ? 0 : -1;
            }
        });

        Set<Long> domainsIdList = questionList.stream().map(questions1 -> questions1.get(0).getDomain().longValue())
                .collect(Collectors.toSet());



        List<SysQuestionDomain> domains = domainService.selectQuestionDomainListByIds(domainsIdList);

        // 三级指标分数
        List<QuestionDomainScore> secondDomainScores=new ArrayList<>();
        for (SysQuestionDomain sysQuestionDomain:domains){
            for (List<SysQuestion> sysQuestions:questionList){
                if(sysQuestionDomain.getDomainId().equals(sysQuestions.get(0).getDomain())){
                    System.out.println(sysQuestionDomain.toString());
                    System.out.println(sysQuestions.size());
                    secondDomainScores.add(ScoreUtils.getDomainScore(sysQuestionDomain,sysQuestions));
                    break;
                }
            }

        }

        return secondDomainScores;
    }



    /**
     * 修改现场诊断记录
     *
     * @param sysCompanyDiagnosis 现场诊断记录
     * @return 结果
     */
    @Transactional
    @Override
    public int updateSysCompanyDiagnosisDomain(SysCompanyDiagnosis sysCompanyDiagnosis)
    {

        List<DomainInfoItemEditVo> domainInfoItemEditVos = JSONUtil.toList(sysCompanyDiagnosis.getDomainInfo(), DomainInfoItemEditVo.class);

        if(CollUtil.isNotEmpty(domainInfoItemEditVos)){
//            List<SysCompanyReportReason> reasons=new ArrayList<>();
//
//            List<SysCompanyReportSuggest> suggests=new ArrayList<>();
//            SysCompanyReportReason sysCompanyReportReason;
//            SysCompanyReportSuggest sysCompanyReportSuggest;
//            for (DomainInfoItemEditVo domainInfoItemEditVo:domainInfoItemEditVos){
//                if("1".equals(domainInfoItemEditVo.getReasonEdit())){
//                    sysCompanyReportReason=new SysCompanyReportReason();
//                    sysCompanyReportReason.setUserId(getLoginUser().getUserId());
//                    sysCompanyReportReason.setDomainId(domainInfoItemEditVo.getDomainId());
//                    // 默认不公开
//                    sysCompanyReportReason.setOpenStatus("2");
//                    sysCompanyReportReason.setContent(domainInfoItemEditVo.getReason());
//                    sysCompanyReportReason.setCreateTime(DateTime.now());
//                    sysCompanyReportReason.setCreateBy(getLoginUser().getUsername());
//                    reasons.add(sysCompanyReportReason);
//                }
//                if("1".equals(domainInfoItemEditVo.getSuggestEdit())){
//                    sysCompanyReportSuggest=new SysCompanyReportSuggest();
//                    sysCompanyReportSuggest.setUserId(getLoginUser().getUserId());
//                    sysCompanyReportSuggest.setDomainId(domainInfoItemEditVo.getDomainId());
//                    // 默认不公开
//                    sysCompanyReportSuggest.setOpenStatus("2");
//                    sysCompanyReportSuggest.setContent(domainInfoItemEditVo.getReason());
//                    sysCompanyReportSuggest.setCreateTime(DateTime.now());
//                    sysCompanyReportSuggest.setCreateBy(getLoginUser().getUsername());
//                    suggests.add(sysCompanyReportSuggest);
//                }
//            }
//
//            if(CollUtil.isNotEmpty(reasons)){
//                sysCompanyReportReasonMapper.insertSysCompanyReportReasonList(reasons);
//            }
//            if(CollUtil.isNotEmpty(suggests)){
//                sysCompanyReportSuggestMapper.insertSysCompanyReportSuggestList(suggests);
//            }

            List<DomainInfoItemVo> domainInfoItemVos = JSONUtil.toList(sysCompanyDiagnosis.getDomainInfo(), DomainInfoItemVo.class);

            sysCompanyDiagnosis.setDomainInfo(JSONUtil.toJsonStr(domainInfoItemVos));
        }





        sysCompanyDiagnosis.setUpdateTime(DateUtils.getNowDate());
        return sysCompanyDiagnosisMapper.updateSysCompanyDiagnosis(sysCompanyDiagnosis);
    }
}
